<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-title filter-item">礼品分类</span>
      <k-select
        v-model="listQuery.typeId"
        class="filter-item user-status"
        type="1"
        :custom-params="{opations:prizeTypeList, label:'lineName',value:'lineId'}"
        @handleSelectEvent="handleFilter"
      />
      <k-input
        v-model.trim="listQuery.key"
        class="filter-item"
        is-search
        placeholder="请输入关键词"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>
    <!-- 创建 roll 房 -->
    <div class="op_container">
      <k-button v-if="authorityHandle(49)" class="top-btn" value="添加礼品" @click.native="addGiftDialog" />
      <!-- <k-button class="top-btn" value="玩法介绍" @click.native="ruleGuideDialog" /> -->
      <div class="top-right">
        <k-button class="top-right-btn" value="分类管理" @click.native="gotoGiftCategorySetting" />

        <el-switch
          v-model="giftState"
          :disabled="!authorityHandle(49)"
          active-color="#3b425d"
          inactive-color="#E9EBF2"
          active-text="开启"
          inactive-text="关闭"
          :active-value="1"
          :inactive-value="0"
          @change="giftStateChange()"
        />
      </div>
    </div>

    <!--表格相关 -->
    <el-table
      :data="prizeTableData"
      fit
      border
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
      @sort-change="sortChange"
    >
      <el-table-column width="80px" type="index" label="序号" align="center" />
      <el-table-column min-width="80px" label="礼品图标" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 80px; height: 80px"
            :src="scope.row.iconUrl"
            :preview-src-list="[scope.row.iconUrl]"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column prop="prizeName" min-width="100px" label="礼品名称" align="center" show-overflow-tooltip />

      <el-table-column v-if="authorityHandle(49)" prop="prizePrice" min-width="100px" label="礼品价格" sortable="custom" align="center">
        <editable-cell v-model="row.prizePrice" slot-scope="{row}" :show-input="row.editMode" @keyup.enter.native="updateGoodsPrice(row)">
          <span slot="content" style="text-align: center;display:block;width:100%;">{{ row.prizePrice }}</span>
        </editable-cell>
      </el-table-column>

      <el-table-column v-else prop="prizePrice" min-width="100px" label="礼品价格" sortable="custom" align="center" />

      <el-table-column prop="typeName" min-width="100px" label="礼品分类" align="center" show-overflow-tooltip />
      <el-table-column prop="superTypeName" min-width="100px" label="父级分类" align="center" show-overflow-tooltip />
      <el-table-column prop="prizeDataName" min-width="100px" label="所属饰品" align="center" show-overflow-tooltip />
      <el-table-column v-if="authorityHandle(49)" min-width="100px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="查看/修改" @click.native="updateActivityDialog(scope.row)" />
            <k-button class="table-btn" value="删除" @click.native="deleteGiftDialog(scope.row.id)" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />
    <!-- 玩法介绍 弹窗 -->
    <k-dialog
      :show-hide.sync="ruleGuide.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="玩法介绍"
      class-name="ruleGuide-dialog"
      :show-foot="false"
      :two-btn="authorityHandle(49)"
      @click="guideSave"
    >
      <div class="dialog-ruleGuide" style="padding:30px">
        <el-form :model="ruleGuideContent" label-width="auto">
          <el-form-item label="内容介绍：" prop="content">
            <quill-editor
              ref="myQuillEditor"
              v-model.trim="ruleGuideContent.content"
              :options="editorOption"
              class="editer"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>

    <!-- 添加礼品 弹窗 -->
    <k-dialog
      :show-hide.sync="addGiftShowFlag"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      :two-btn="true"
      @click="saveGiftEvent"
    >
      <div class="dialog_container">
        <el-form label-width="100px">
          <el-form-item label="礼品分类：">
            <el-select v-model="prizeTypeItem" filterable placeholder="请选择" value-key="lineId" clearable @change="goodSelectChange">
              <el-option
                v-for="item in prizeTypeList"
                :key="item.lineId"
                :label="item.lineName"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <div v-if="prizeTypeItem.type===5">
            <el-form-item label="礼品名称：">
              <el-select v-model="addGiftModel.prizeDataId" clearable placeholder="请选择" filterable>
                <el-option
                  v-for="item in goodsPlatformList"
                  :key="item.lineId"
                  :label="item.lineName"
                  :value="item.lineId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item label="礼品名称：">
              <el-input v-model="addGiftModel.prizeName" placeholder="请输入礼品名称" />
            </el-form-item>
            <el-form-item v-show="prizeTypeItem.type===2" label="所属饰品：">
              <el-select v-model="addGiftModel.prizeDataId" clearable placeholder="请选择" filterable>
                <el-option
                  v-for="item in goodsList"
                  :key="item.lineId"
                  :label="item.lineName"
                  :value="item.lineId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="礼品价格：">
              <el-input-number v-model="addGiftModel.prizePrice" :precision="2" controls-position="right" placeholder="请输入数值" :step="0.01" />
            </el-form-item>
            <el-form-item label="礼品图标：">
              <k-upload-file
                ref="upload1"
                v-model="addGiftModel.iconUrl"
                upload-style="img"
                @successUpload="successUpload($event)"
              />
              <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
            </el-form-item>
          </div>
        </el-form>
        <!-- replace(1,"汰换券"),
    lucky(2,"幸运券"),
    coin(3,"95币"),
    prize(4,"实物"),
    goods(5,"平台饰品"),; -->
      </div>
    </k-dialog>
  </div>
</template>
<script>
import { getGoodsPlatformList, getLuckyList, getPrizeTypeList, listPrizeData, savePrizeData, updatePrizeData, deletePrizeData, updateGoodsPrice, getPrizeDescribe, setPrizeDescribe, getPrizeStatus, setPrizeStatus } from '@/api/task/index'
import Pagination from '@/components/Pagination'
import EditableCell from '@/components/EditableCell'

export default {
  components: { Pagination, EditableCell },
  data() {
    return {
      prizeTypeItem: {
        lineId: undefined,
        lineName: '',
        lineCheck: false,
        type: -1
      },
      addGiftModel: {
        id: undefined,
        typeId: undefined, // 礼品分类',
        superTypeId: undefined, // 礼品上级分类',
        prizeName: undefined, // 礼品名称',
        prizeDataId: undefined, // 礼品所属饰品',
        prizePrice: undefined, // 礼品价格',
        iconUrl: '' // 礼品图标'
      },
      prizeTypeList: [],
      goodsPlatformList: [],
      giftCategoryList: [],
      goodsList: [],
      dayTaskModel: 0,
      coinModel: 0,
      giftState: 0,
      redrules: {
        envelopeNum: [
          { required: true, message: '请输入红包个数', trigger: 'blur' }
        ]
      },
      giveType: 1,
      settingType: 'setting1',
      dialogStatus: 'create',
      textMap: {
        update: '修改礼品',
        create: '添加礼品'
      },
      updateButtonState: false,
      radioState: false,
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '', // 排序 正向(asc)逆向(desc),
        typeId: undefined,
        key: '' // 箱子名称或关键词 箱子配置界面所用'
      },
      prizeTableData: [],
      winnerUserList: [],
      userList: [],
      ruleGuideContent: {
        content: ''
      },
      editorOption: { //  富文本编辑器配置
        placeholder: '请输入内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ 'header': 1 }, { 'header': 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
            [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
            [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
            [{ 'direction': 'rtl' }], // 文本方向
            [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
            [{ 'font': [] }], // 字体
            [{ 'align': [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image'] // 上传图片、上传视频
          ]
        }
      },
      timeValue: '',
      timeCotinue: '',
      conditions: {
        keyword: null
      },
      creatRollRoom: {
        showHide: false
      },
      userListDialog: {
        showHide: false
      },
      ruleGuide: {
        showHide: false
      },
      addRobots: {
        showHide: false
      },
      updateBabyNum: {
        showHide: false
      },
      addGiftShowFlag: false,
      amount: 0
    }
  },
  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null
    }
  },
  created() {
    this.loadData()
    this.getPrizeTypeList()
    this.getPrizeStatus()
    this.getPrizeDescribe()
  },
  methods: {
    // 表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
      this.listQuery.sort = column.prop
      if (column.order === 'ascending') {
        this.listQuery.direction = 'asc'
      } else if (column.order === 'descending') {
        this.listQuery.direction = 'desc'
      }
      this.handleFilter()
    },
    updateGoodsPrice(row) {
      updateGoodsPrice({ id: row.id, prizePrice: row.prizePrice, readyStatus: false }).then(res => {
        if (!res.data.success) {
          this.$message.error(res.data.msg)
        }
      })
    },
    getPrizeTypeList() {
      getPrizeTypeList().then(res => {
        this.prizeTypeList = res.data
      })
    },
    getPrizeStatus() {
      getPrizeStatus().then(res => {
        this.giftState = res.data ? 1 : 0
      })
    },
    goodSelectChange(v, prizeDataId) {
      console.log('prizeDataId: ', this.prizeTypeItem)
      const flag = prizeDataId === undefined || prizeDataId === null ? v.type : v
      switch (flag) {
        case 2:
          getLuckyList().then(res => {
            this.goodsList = res.data
          })
          break
        case 5:
          getGoodsPlatformList({ goodsId: prizeDataId }).then(res => {
            this.goodsPlatformList = res.data
          })
          break
      }
      // this.prizeTypeItem.lineId = prizeDataId
    },
    saveGiftEvent() {
      this.addGiftModel.typeId = this.prizeTypeItem.lineId
      if (this.dialogStatus === 'create') {
        savePrizeData(this.addGiftModel).then(res => {
          if (res.data.success) {
            this.$message.success('保存成功')
            this.loadData()
          } else {
            this.$message.success(res.data.msg)
          }
        })
      } else {
        updatePrizeData(this.addGiftModel).then(res => {
          if (res.data.success) {
            this.$message.success('修改成功')
            this.$resetForm(this.addGiftModel)
            this.loadData()
          } else {
            this.$message.success(res.data.msg)
          }
        })
      }
      this.addGiftShowFlag = false
    },
    deleteGiftDialog(id) {
      this.$confirm('确定删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePrizeData({ id }).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.success(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    addGiftDialog() {
      this.$resetForm(this.addGiftModel)
      this.prizeTypeItem = {
        lineId: undefined,
        lineName: '',
        lineCheck: false,
        type: -1
      }
      this.prizeTypeItem.lineId = undefined
      this.prizeTypeItem.lineName = undefined
      this.prizeTypeItem.type = undefined
      this.dialogStatus = 'create'
      this.addGiftShowFlag = true
    },
    updateActivityDialog(row) {
      this.dialogStatus = 'update'
      this.addGiftShowFlag = true
      this.goodSelectChange(row.superTypeId, row.prizeDataId)
      this.addGiftModel.id = row.id
      this.addGiftModel.typeId = row.typeId
      this.addGiftModel.superTypeId = row.superTypeId
      this.addGiftModel.prizeName = row.prizeName
      this.addGiftModel.prizeDataId = row.prizeDataId
      this.addGiftModel.prizePrice = row.prizePrice
      this.addGiftModel.iconUrl = row.iconUrl
      this.prizeTypeItem = {
        lineId: row.typeId,
        lineName: row.typeName,
        lineCheck: false,
        type: row.superTypeId
      }
      this.$log(this.prizeTypeItem)
    },
    // 分类管理
    gotoGiftCategorySetting() {
      this.$router.push({ path: '/taskwall/giftcategorymanager' })
    },
    loadData() {
      listPrizeData(this.listQuery).then(res => {
        this.totalRows = res.data.totalRows
        this.prizeTableData = res.data.rows.map(row => {
          return {
            ...row,
            editMode: false
          }
        })
      })
    },
    // 保存玩法管理
    guideSave() {
      const contents = this.ruleGuideContent.content
      setPrizeDescribe({ 'data': contents }).then(res => {
        this.ruleGuide.showHide = false
      })
    },
    // 加载玩法管理
    getPrizeDescribe() {
      getPrizeDescribe().then(res => {
        this.ruleGuideContent.content = res.data
      })
    },
    // 任务状态
    giftStateChange(event) {
      setPrizeStatus({ 'data': this.giftState === 1 }).then(res => {
        this.$message.success('操作成功')
      })
    },

    // 搜索查询事件
    handleFilter() {
      this.listQuery.pager.pageNo = 1
      this.loadData()
    },
    successUpload(data) {
      this.addGiftModel.iconUrl = data
    },
    ruleGuideDialog() {
      this.ruleGuide.showHide = true
    }
  }

}
</script>
<style lang="scss" scoped>
$menuText:#14162E; // 侧边栏字体颜色
$hoverColor:#1D143C;// 鼠标停留主色调浅色
$mainColor:#3b425d;// 主色调
::v-deep .el-radio__label{
  display: none;
}

.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;
  display: flex;
  flex-direction: row;
  align-items: center;
  .filter-item {
    &.weekselect{
      margin-left: 20px;
      margin-top: 5px;
    }
  }
  .kInput{
    position:absolute;
    right: 20px;
  }
  .filter-title{
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162E;
  }
  .user-status{
    margin-right: 20px;
  }
  ::v-deep .el-range-editor.el-input__inner {
    width: 250px;
  }
  ::v-deep .kSelect .el-select .el-input .el-input__inner {
    width: 150px;
  }
}
.op_container{
  position: relative;
  .top-btn{
    margin: 30px 0px 30px 0px;
    font-size: 14px;
    color: #ffffff;
    &:nth-of-type(2){
      margin-left: 10px;
    }
    &:nth-of-type(3){
      margin-left: 10px;
    }
    &:nth-of-type(4){
      margin-left: 10px;
    }
  }
  .top-right{
    position: absolute;
    right: 20px;
    top: 30px;
    .top-right-btn{
      margin-right: 20px;
      background-color: #F8F7FB;
      border-color: transparent;
      color: #14162E;
      &:hover{
        color: #ffffff;
        background-color: $mainColor;
      }
      &:active{
        color: #14162E;
      }
    }
  }
}
.kSelect .el-select .el-input .el-input__inner{
  width: 124px;
}
::v-deep .el-select .el-input.is-focus .el-input__inner {
    border-color: $mainColor;
}
::v-deep .el-input__inner:focus {
    border-color: $mainColor;
}
.el-form-item__label-wrap .el-form-item__label{
  float: none;
}

.dialog_container{
  padding: 40px 120px;
}

.editer {
  width: 500px;
  border-radius: 8px;
  float: left;
  box-sizing: border-box;
  color: #606266;
  ::v-deep .ql-container {
    height: 270px;
    border-radius: 0px 0px 8px 8px;
  }
  ::v-deep .ql-toolbar.ql-snow {
    border-radius: 8px 8px 0px 0px;
  }
}
::v-deep .el-switch__label.is-active {
    color: $mainColor;
}

.addBox_dialog{
  display: flex;
  flex-direction: column;
  justify-content: center;
  ::v-deep .el-dialog__body{
    width: 678px;
    margin: 40px 80px;
 }
::v-deep .el-select .el-select__tags>span {
			display: none;
	}
  .el-tag + .el-tag {
    margin-left: 10px;
  }
   .el-tag {
    color: $mainColor;
    background-color: #ffffff;
    border-color: $mainColor;
    ::v-deep .el-tag__close {
      color: $mainColor;
    }
    ::v-deep .el-icon-close:hover {
      color:#ffffff;
      background: $mainColor;
    }
  }
}
.setting_dialog{
 ::v-deep .el-dialog__body{
    width: 600px;
  }
   .ration_div{
     display: flex;
     justify-content: center;
  }
  ::v-deep .el-radio-button__inner{
    &:hover{
      color: $mainColor;
    }
  }
  .dialog-warningSetting{
    ::v-deep.el-input{
      width: 110px;
    }
  }
}
</style>
